<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="物料类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                v-decorator="['materialType', {rules: [{required: true, message: '请选择物料类型!'}]}]"
                placeholder="请选择物料类型"
                dictCode="material_type"
                @change="handleMaterialTypeChange"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="物料" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                v-decorator="['materialId', {rules: [{required: true, message: '请选择物料!'}]}]"
                placeholder="请选择物料"
                dict="wms_material,name,id"
                :triggerChange="true"
                :disabled="!materialType"
                :condition="materialCondition"
                @change="handleMaterialChange"/>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="物料编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['materialCode']"
                placeholder="物料编码"
                disabled/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['materialName']"
                placeholder="物料名称"
                disabled/>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['specification']"
                placeholder="规格"
                disabled/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['color']"
                placeholder="颜色"
                disabled/>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="库位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                v-decorator="['locationId']"
                placeholder="请选择库位"
                dict="wms_warehouse_location,name,id"
                :condition="locationCondition"
                @change="handleLocationChange"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['batchNo']"
                placeholder="请输入批次号"
                @change="handleBatchNoChange"/>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                v-decorator="['quantity', {rules: [{required: true, message: '请输入数量!'}]}]"
                placeholder="请输入数量"
                style="width: 100%"
                :min="0"
                :precision="2"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-decorator="['unit']"
                placeholder="单位"
                disabled/>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="24">
          <a-col :span="24">
            <a-alert type="info" v-if="inventoryInfo">
              <div slot="message">
                当前库存: <strong>{{ inventoryInfo.quantity }}</strong> {{ inventoryInfo.unit }}
              </div>
            </a-alert>
            <a-alert type="warning" v-if="showInventoryWarning">
              <div slot="message">
                出库数量超过当前库存!
              </div>
            </a-alert>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { getAction } from '@/api/manage'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
  
  export default {
    name: "DetailModal",
    components: {
      JDictSelectTag,
      JSearchSelectTag
    },
    data () {
      return {
        title: "添加明细",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        materialType: '',
        materialCondition: {},
        locationCondition: {},
        inventoryInfo: null,
        showInventoryWarning: false
      }
    },
    methods: {
      show(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record || {});
        this.materialType = '';
        this.inventoryInfo = null;
        this.showInventoryWarning = false;
        this.visible = true;
        
        // 设置库位条件
        if (this.model.warehouseId) {
          this.locationCondition = {
            warehouse_id: this.model.warehouseId
          };
        }
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            
            // 设置仓库ID
            values.warehouseId = that.model.warehouseId;
            
            that.$emit('ok', values);
            that.confirmLoading = false;
            that.close();
          }
        })
      },
      handleCancel() {
        this.close();
      },
      close() {
        this.visible = false;
      },
      handleMaterialTypeChange(value) {
        this.materialType = value;
        this.materialCondition = {
          material_type: value
        };
        // 清空物料相关字段
        this.form.setFieldsValue({
          materialId: undefined,
          materialCode: undefined,
          materialName: undefined,
          specification: undefined,
          color: undefined,
          unit: undefined
        });
        
        // 清空库存信息
        this.inventoryInfo = null;
        this.showInventoryWarning = false;
      },
      handleMaterialChange(value) {
        if (value) {
          // 根据物料ID获取物料信息
          getAction('/wms/material/queryById', {id: value}).then(res => {
            if (res.success) {
              const material = res.result;
              this.form.setFieldsValue({
                materialCode: material.code,
                materialName: material.name,
                specification: material.specification,
                color: material.color,
                unit: material.unit
              });
              
              // 查询库存
              this.queryInventory();
            }
          });
        }
      },
      handleLocationChange() {
        this.queryInventory();
      },
      handleBatchNoChange() {
        this.queryInventory();
      },
      queryInventory() {
        const materialCode = this.form.getFieldValue('materialCode');
        const warehouseId = this.model.warehouseId;
        const locationId = this.form.getFieldValue('locationId');
        const batchNo = this.form.getFieldValue('batchNo');
        
        if (materialCode && warehouseId) {
          const params = {
            materialCode: materialCode,
            warehouseId: warehouseId
          };
          
          if (locationId) {
            params.locationId = locationId;
          }
          
          if (batchNo) {
            params.batchNo = batchNo;
          }
          
          getAction('/wms/inventory/queryByMaterial', params).then(res => {
            if (res.success && res.result) {
              this.inventoryInfo = res.result;
              
              // 检查出库数量是否超过库存
              const quantity = this.form.getFieldValue('quantity');
              if (quantity && quantity > res.result.quantity) {
                this.showInventoryWarning = true;
              } else {
                this.showInventoryWarning = false;
              }
            } else {
              this.inventoryInfo = null;
              this.showInventoryWarning = false;
            }
          });
        }
      }
    }
  }
</script>

<style scoped>
</style> 